
<?php
include('../Connections/KRAPPERCON.php');
include ("../Connections/Accesos.php");
$buscar = false;
$found = false;

$cl_doc = '';
$rf_doc = '';
$mon_md = '';
$mon_ml = '';
$emisor = '';
$via_pag = '';
$banco = '';
$moneda = '';
$status = '';
$itf = '';

$doc = '';
$fecdoc = '';
$status = '';
$usrid = '';
$feccre = '';

$cod_emisor = '';
$nom_emisor = '';
$dir_emisor = '';

$oper = '';

if (isset($_POST['oper'])){
$oper = $_POST['oper'];
}

if (isset($_POST['doc']) && $oper == 'view'){
$buscar = true;
$doc = $_POST['doc'];

/*
`idPago`,
`refPago`,
`viaPago`,
`monPago`,
`impPago`,
`impPEN`,
fecDoc,
`feccre`,
`emiPag`,
`agePag`,
`claPag`
*/

$sql = "call sp_getCompenCab('".$doc."');";
doEcho($sql);
$res = $mysqli->query($sql);
	if ($res){
		if ($row = $res->fetch_assoc()){
			$found = true;
			$cl_doc = $row['claPago'];
			$fc_doc = $row['fecDoc'];
			$rf_doc = $row['refPago'];
			$itf = $row['itfPago'];
			$mon_md = $row['impPago'];
			$mon_ml = $row['impPEN'];
			$emisor = $row['emiPago'];
			$via_pag = $row['viaPago'];
			$banco = $row['agePago'];
			$moneda = $row['monPago'];
			$feccre = $row['feccre'];
			$usrid = $row['UserID'];
		}
	
	$res->close();
	$mysqli->check_result();
	}
	
	if ($found){
	$sql = '';
		if ($cl_doc=='FC'){
		$sql = "select ProveedID,ProveedRaz,ProveedNIF,ProveedDir from tt_proveedor where ProveedID = '".$emisor."';";
		doEcho($sql);
		$res = $mysqli->query($sql);
			if ($res && $row=$res->fetch_assoc()){
				$cod_emisor = $row['ProveedID'];
				$nom_emisor = $row['ProveedRaz'];
				$nif_emisor = $row['ProveedNIF'];
				$dir_emisor = $row['ProveedDir'];
			$res->close();
			$mysqli->check_result();
			}
		}
		elseif ($cl_doc=='FV'){
		$sql = "select ClientID,ClientNom,ClientApePat,ClientApeMat,ClientNIF,ClientDirec from tt_cliente where ClientID = '".$emisor."';";
		doEcho($sql);
		$res = $mysqli->query($sql);
			if ($res && $row=$res->fetch_assoc()){
				$cod_emisor = $row['ClientID'];
				$nom_emisor = $row['ClientNom']." ".$row['ClientApePat'].' '.$row['ClientApeMat'];
				$nif_emisor = $row['ClientNIF'];
				$dir_emisor = $row['ClientDirec'];
			$res->close();
			$mysqli->check_result();
			}
		}
	}
}
?>
<div>
<input name="input"  type="button"  value="Nuevo" onclick="nuevaComp()" />&nbsp;
<input name="input"  type="button"  value="Grabar" onclick="saveComp()" />&nbsp;
<input name="input" type="button" value="Anular Compensación" onclick="anularComp()" />&nbsp;
<input name="input" type="button"  value="Imprimir" onclick="" />&nbsp;&nbsp;&nbsp;
<input type="text" name="t_comp_ndoc" id="t_comp_ndoc" onkeypress="enterComp(event)" />
</div>
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="tbl_cmp_dat">

    <?php 
	if ($found){
	?>
  <tr>
    <td colspan="4">
    <div class="subTit">
	<?php 
    echo "Documento de Compensaci&oacute;n ".$doc." creador por ".$usrid." el ".$feccre." ".$status;
    ?>
    </div>    </td>
  </tr>
    <?php 
	
	}
	?>
  <tr>
    <td>Clase de Compensación :</td>
    <td>
    <select name="cb_comp_type" id="cb_comp_type" onChange="chgClaComp(true);">
      <option value="FV">Facturas de Venta</option>
      <option value="FC"  selected="selected">Facturas de Compra</option>
        </select>
    </td>
    <td>Documento:</td>
    <td><span id="sp_comp_nd" style="font-weight:bold;"></span></td>
  </tr>
  <tr>
    <td>Fecha Documento :</td>
    <td><input name="t_cmp_fecdoc" type="text" title="Fecha de Documento" value="<?php echo $hoy;?>" onChange="calcML1();" id="t_cmp_fecdoc" size="15" maxlength="10" class="tcal clsReq"></td>
    <td>Via Pago:</td>
    <td>
      <select name="cb_via_pag" id="cb_via_pag">
        <option value="CH">Cheque</option>
        <option value="EF">Efectivo - Caja Chica</option>
        <option value="DC">Depósito en Cuenta</option>
        <option value="TR">Transferencia</option>
      </select>
    </td>
  </tr>
  <tr>
    <td>Referencia :</td>
    <td>
      <input name="t_cmp_ref" class="clsReq" type="text" id="t_cmp_ref" size="30" maxlength="30">
    </td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>Monto :</td>
    <td>
      <input name="t_cmp_md"type="text" class="qt clsReq" id="t_cmp_md" size="15" onChange="mr(this);calcML1();"  maxlength="10">
    </td>
    <td>Moneda</td>
    <td><select name="cb_cmp_mon" id="cb_cmp_mon" onchange="changeMdCmp();">
      <?php 
	  $moneda = 'PEN';
	  include ('../Query_Min/getMonedas.php'); ?>
    </select></td>
  </tr>
  <tr>
    <td>Monto ML :</td>
    <td>
      <input name="t_cmp_ml" type="text" id="t_cmp_ml" class="qt clsReq" disabled='disabled' size="15" maxlength="10">
    </td>
    <td>ITF :</td>
    <td>
      <input name="t_cmp_itf" type="text" class="qt" id="t_cmp_itf" onchange="mr(this)" size="15" maxlength="10" />
    </td>
  </tr>
  <tr>
    <td>Emisor :</td>
    <td colspan="3"><input name="t_codemi" type="text" id="t_codemi" disabled="disabled"  class="clsReq"  size="12" maxlength="10" />
        <input name="t_nomemi" type="text"  disabled="disabled" id="t_nomemi" size="40" />
        <input value="..." type="button" onclick="searchEmisor()" />
        &nbsp;
        <input type="submit" name="btn_getdocs" id="btn_getdocs" value="Traer Doc.Pendientes" onclick="getCmpDocPendientes(null,null)" />        </td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td colspan="3">
      <input name="t_diremi" type="text" id="t_diremi" size="50" maxlength="50"  disabled="disabled"  />
    </td>
  </tr>
  <tr>
    <td>Agencia :</td>
    <td>
      <select name="cb_cmp_bco" id="cb_cmp_bco" style="width:200px;">
       <?php include ('../Query_Min/getBancos.php'); ?>
      </select>
    </td>
    <td>Total Docum :</td>
    <td><span style="font-weight:bold;" id="sp_sum_pago"></span></td>
  </tr>
  <tr class="clsRowFc">
    <td>
    <span id="sp_pret" class="noView">
        <?php 
	$porret = 0;
	$sql = "call sp_selNumerador(0,'RETENC');";
	$res = $mysqli->exeQuery($sql);
	if($res){
		if ($row=$res->fetch_assoc()){
			$porret = $row['NumerVal'];
			echo $porret;
		}
	$res->close();
	$mysqli->check_result();
	}	
	?>
    </span>
    <strong>Valor mínmo afecto:    </strong></td>
    <td>
    <?php 
	$minret = 0;
	$sql = "call sp_selNumerador(0,'MAXRET');";
	$res = $mysqli->exeQuery($sql);
	if($res){
		if ($row=$res->fetch_assoc()){
			$minret = $row['NumerVal'];
		}
	$res->close();
	$mysqli->check_result();
	}
	?>
      <input type="text" class="qt disabled" name="t_minret" value="<?php echo myRound($minret);?>" id="t_minret" disabled="disabled"  />
    </td>
    <td><strong>Monto Detracción :</strong></td>
    <td>
      <input type="text" name="t_monret" id="t_monret" class="qt disabled" disabled="disabled" />
    </td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td colspan="4">
   
    <table width="100%" border="1" cellspacing="0" rules="all" id="tbl_cmp_doc" class="tableIn tblSort" cellpadding="0">
    <thead>
     <?php if ($found){ ?>
     <tr>      	
        <th scope="col">&nbsp;</th>
        <th scope="col">Documento</th>
        <th scope="col">Referencia</th>
        <th scope="col">Fecha</th>
        <th scope="col">Vencimiento</th>
        <th scope="col">Razon Social</th>
        <th scope="col">MON</th>
        <th scope="col">Monto(inc.IGV)          </th>		
		<th scope="col">IGV</th>       
        <th scope="col">Saldo</th>
        <th scope="col">Ret(MD)</th>
        <th scope="col">Det(MD)</th>
      	<th scope="col">Pago</th>  
        </tr>
     <?php } else { ?>
      <tr>      	
        <th scope="col">&nbsp;</th>
        <th scope="col">Documento</th>
        <th scope="col">Referencia</th>
        <th scope="col">Fecha</th>
        <th scope="col">Vencimiento</th>
        <th scope="col">Razon Social</th>
        <th scope="col">MON</th>
        <th scope="col">Monto(inc.IGV)          </th>		
		<th scope="col">IGV</th>
        <th scope="col">Saldo</th>
      	<th scope="col" class="th_det">Detr.(%)</th>
		<th scope="col"  class="th_det">Detr.</th>     
        <th scope="col" class="th_ret">Ret.(%)</th>
        <th scope="col" class="th_ret">Rete.</th>
        <th scope="col">por Compensar</th>
        <th scope="col">Nuevo Saldo</th>
        </tr>
        <?php } ?>
        </thead>
        <tbody>
        
        <?php if ($found) { 
		$sql = "call sp_getDetCompens('".$doc."','".$cl_doc."');";
		$res = $mysqli->query($sql);
		//doEcho($sql);
		if ($res){
			while($row = $res->fetch_assoc()){
			
			$fecha_doc = '';
			$fecha_ven='';
			$emisor_fac = '';
			$moneda_fac = '';
			$monto_fac = '';
			$monto_comp = '';
			$sald_act = '';
			$cond_vend = '';
			$monto_ret = '';
			$igv_fac = 0;
			
				if ($cl_doc=='FV'){
				$fecha_doc = $row['FactFecFac'];
				$cond_vend = $row['CondVenID'];
				$dias = substr($cond_vend,1);
					//echo "Dias:".$dias;
				$fecha_ven = addDays($fecha_doc,$dias);
				//$fecha_ven='';
				$ref_fac = $row['FactFolio'];
				$emisor_fac = $row['ClientNom'].' '.$row['ClientApePat'].' '.$row['ClientApeMat'];
				$moneda_fac = $row['MoneyID'];
				$igv_fac = $row['FactIva'];
				$monto_fac = $row['FactNet']+$row['FactIva'];
				$monto_det = $row['montoDet'];
				$monto_ret = $row['montoRet'];				
				$monto_per = $row['montoPer'];	
				$monto_comp = $row['MonComp'];
				$sald_act = $monto_fac - $monto_comp;
				}
				elseif ($cl_doc =='FC') {
				$fecha_doc = $row['FactCompFeFc'];
				$fecha_ven=$row['FactFecVen'];
				$ref_fac = $row['FacturaRef'];
				$emisor_fac = $row['ProveedRaz'];
				$moneda_fac = $row['MoneyID'];
				$igv_fac = $row['FactImpuesto'];
				$monto_det = $row['montoDet'];
				$monto_ret = $row['montoRet'];				
				$monto_per = $row['montoPer'];								
				$monto_fac = $row['FactImporte']; //incluye impuestos
				$monto_comp = $row['MonComp'];
				//$prc_det = $row['valPercent'];
				$sald_act = $monto_fac - $monto_comp;
				}
		?>
        <!-- 
         <th scope="col">&nbsp;</th>
        <th scope="col">Documento</th>
        <th scope="col">Referencia</th>
        <th scope="col">Fecha</th>
        <th scope="col">Vencimiento</th>
        <th scope="col">Razon Social</th>
        <th scope="col">MON</th>
        <th scope="col">Monto(inc.IGV)          </th>		
		<th scope="col">IGV</th>       
        <th scope="col">Saldo</th>
      	<th scope="col">Detr.(%)</th>
		<th scope="col">Detr.</th>     
        -->
        <tr>
        <td align="center"><input name="" type="button" onClick="delPosComp(this);"  value="X"></td>
        <td><span class="clsDoc" title="<?php $row['documID'];?>" style="font-weight:bold"><?php echo $row['documID'];?></span>         
        <td class="clsRef"><?php echo $ref_fac;?></td>
        <td class="clsFec"><?php echo $fecha_doc;?></td>
        <td class="clsVen"><?php echo $fecha_ven;?></td>
        <td class="clsNom"><?php echo $emisor_fac; ?></td>
        <td class="clsMon"><?php echo $moneda_fac;?></td>
        <td class="clsImp qt"><?php echo rnd($monto_fac);?></td>
        <td class="clsIgv qt"><?php echo rnd($igv_fac);?></td>
        <td class="clsSald qt"><?php echo rnd($sald_act); ?></td>
         <td class="clsMRet qt"><?php echo rnd($monto_ret); ?></td>
          <td class="clsMDet qt"><?php echo rnd($monto_det); ?></td>
        <td class="clsComp qt"><?php echo rnd(abs($row['montoMD']));?></td>
        </tr>
        <?php 
			}
			$res->close();
			$mysqli->check_result();
		}
		?>
        
        <?php 
		}
		else {
        ?>
        <!--         
        <th scope="col">&nbsp;</th>
        <th scope="col">Documento</th>
        <th scope="col">Referencia</th>
        <th scope="col">Fecha</th>
        <th scope="col">Vencimiento</th>
        <th scope="col">Razon Social</th>
        <th scope="col">MON</th>
        <th scope="col">Monto(inc.IGV)          </th>		
		<th scope="col">IGV</th>
        <th scope="col">Saldo</th>
      	<th scope="col">Detr.(%)</th>
		<th scope="col">Detr.</th>     
        <th scope="col">por Compensar</th>
        <th scope="col">Nuevo Saldo</th>
        -->
      <tr class="trLast noView" onKeyPress="" >
        <td align="center"><input name="" type="button" onClick="delPosComp(this);"  value="X"></td>
        <td>
          <input class="clsDoc" style="font-weight:bold" onChange="calcDocsComp();" type="text" >        </td>
        <td class="clsRef">&nbsp;</td>
        <td class="clsFec">&nbsp;</td>
        <td class="clsVen">&nbsp;</td>
        <td class="clsNom">&nbsp;</td>
        <td class="clsMon">&nbsp;</td>
        <td class="clsImp qt">&nbsp;</td>
        <td class="clsIgv qt">&nbsp;</td>
        <td class="clsComp qt">&nbsp;</td>
        <td class="th_det clsPDet qt">&nbsp;</td>
        <td class="th_det clsMDet qt">&nbsp;</td>
        <td class="th_ret" align="center">
          <input type="checkbox" class="clsPRet" onchange="calcDocsComp();" />
        </td>
        <td class="th_ret clsMRet qt">&nbsp;</td>
        <!-- <td class="clsRD qt">&nbsp;</td> -->
        <td>
          <input class="qt clsVal" onChange="mr(this);calcDocsComp();"  type="text">        </td>
        <td class="clsSald qt">&nbsp;</td>
        </tr>
        <?php 
		}
		?>
        </tbody>
      <tfoot>
      <tr>
        <td>&nbsp;</td>
        <td><input name="btn_adddoc" onClick="addDocComp();" value="Agregar Documento" type="button"></td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
         <td>&nbsp;</td>
        <td>&nbsp;</td>
        <?php if (!$found) { ?>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>      
        <?php }?>
        </tr>
      </tfoot>
    </table></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>
<script type="text/javascript">


<?php 
if ($buscar){
	if ($found){
	?>
	GEBI('cb_comp_type').value ='<?php echo $cl_doc;?>';
	GEBI('t_cmp_fecdoc').value ='<?php echo $fc_doc;?>';
	GEBI('t_cmp_ref').value ='<?php echo $rf_doc;?>';
	GEBI('t_cmp_md').value ='<?php echo $mon_md; ?>';
	GEBI('t_cmp_ml').value ='<?php echo $mon_ml;?>';
	GEBI('t_codemi').value ='<?php echo $cod_emisor; ?>';
	GEBI('t_nomemi').value ='<?php echo $nom_emisor; ?>';
	GEBI('t_diremi').value ='<?php echo $dir_emisor; ?>';
	GEBI('cb_via_pag').value ='<?php echo $via_pag;?>';		
	GEBI('cb_cmp_bco').value = '<?php echo $banco; ?>';
	GEBI('cb_cmp_mon').value = '<?php echo $moneda; ?>';
	GEBI('t_cmp_itf').value = '<?php echo $itf; ?>';
	GEBI('sp_comp_nd').innerHTML = '<?php echo $doc;?>';
	noEditComp();
	<?php 
	}
	else {
	?>
	alert('El documento <?php echo $doc;?> no existe.');
	<?php
	}
}

if (!$found){
?>
for(var x=0;x<5;x++){
addDocComp();
}
<?php 
}
?>

function calcML1(){
	var mon = GEBI('cb_cmp_mon').value;
	var fecha = GEBI('t_cmp_fecdoc').value;
	var monto = GEBI('t_cmp_md').value;
	
	if (monto==0){
	GEBI('t_cmp_ml').value = '0.00';
	return;
	}
	
	if(mon != 'PEN'){
		$.post('Query_Min/getMoneyConv.php',
		{ 
		  from : mon ,
		  fecha : fecha,
		  monto : monto
		},
		function(d){
			var obj = eval("("+d+")");
			if (obj.value == '0' || obj.value == null || $.trim(obj.value) == '')
			{
				showError(fecha+':No existe TC '+mon+'->PEN');
				GEBI('t_cmp_ml').value = '0.00';
			}
			else {
			GEBI('t_cmp_ml').value = myRound(obj.value);
			}
		});
	}
	else {
		GEBI('t_cmp_ml').value = myRound(monto);
	}
	calcDocsComp_2();
}

function changeMdCmp(){
var c = 0;
$("#tbl_cmp_doc tbody tr").not(".trLast").each(function(){
	var fila = $(this);
	var mon = fila.find('.clsMon').html();
	if (mon!=GEBI('cb_cmp_mon').value){
		fila.remove();
		c++;
	}
});

	calcML1();

	for(var x=0;x<c;x++){
	addDocComp();
	}
}

function addDocComp(){
	var newrow = $("#tbl_cmp_doc tbody .trLast").clone().removeClass('noView').removeClass('trLast');
	$("#tbl_cmp_doc tbody").append(newrow);
	return newrow;
}

function chgClaComp(del){
	//if ($("#tbl_cmp_doc tbody tr").not(".trLast").length > 0){	
	//}
	if (del){
	$("#tbl_cmp_doc tbody tr").not(".trLast").remove();
	$("#t_codemi,#t_nomemi,#t_diremi").val('');
	}
	if (GEBI('cb_comp_type').value == 'FV'){
		$(".clsRowFc").addClass('noView');
		$(".th_ret").removeClass('noView');
		$(".th_det").addClass('noView');
		//GEBI('th_conc').innerHTML = 'Retenido';
	}
	else if (GEBI('cb_comp_type').value == 'FC'){
		$(".clsRowFc").removeClass('noView');
		$(".th_ret").addClass('noView');
		$(".th_det").removeClass('noView');
		//GEBI('th_conc').innerHTML = 'Detracción';
	}
}

function delPosComp(obj){
	var fila=$(obj).parent().parent().remove();
	
	calcDocsComp();
}

function calcDocsComp_2(){
// Calcular el % Detracción y % Retención

	var tot_detra = 0;
	var tot_reten = 0;
	var tot_perce = 0;
	var imp_detra = 0;
	var total_ml = pFloat(GEBI('t_cmp_ml').value);
	var afecto_min = pFloat(GEBI('t_minret').value);
	var cla_comp = GEBI('cb_comp_type').value;
	var pret = pFloat(GEBI('sp_pret').innerHTML);
	//if(total_ml >= t_minret) {
		//pret = pret * 0.01;
		// APlicar los cálculo de Detracción
		
		
		if (cla_comp == 'FC'){
				$("#tbl_cmp_doc tbody tr").not(".trLast").each(function(){
						var fila=$(this);				
						fila.find('.clsMDet').html('');			
						var pag = pFloat(fila.find('.clsVal').valx());
						var imp = pFloat(fila.find('.clsImp').valx());
						var pdet = pFloat(fila.find('.clsPDet').html())*0.01;
						var mon_det = 0;
						var mon_ret = 0;
						
						if ( imp >= afecto_min ) {
						mon_det = pdet * imp ;
						imp_detra = imp_detra + mon_det;
						}
						//alert(mon_det);
						if (mon_det > 0){
						// Si tiene detracción
						fila.find('.clsMDet').html(myRound(mon_det));
							if (pag < mon_det && pag > 0 ){
							//showError('Debe compensar al menos el valor de la Detracción.');
							fila.find('.clsVal').val('0.00');
							calcDocsComp();
							}
						tot_detra = tot_detra + imp;
						}	
												
						//tot_reten = tot_reten + mon_ret;
		
				});
				
				GEBI('t_monret').value = myRound(imp_detra);
				
				total_ml = total_ml - tot_detra;
				
				if (isAgenteRet){
				//alert(total_ml);
				//Aplicar el cálculo de Retención
				$("#tbl_cmp_doc tbody tr").not(".trLast").each(function(){
						var fila=$(this);	
									
						fila.find('.clsMRet').html('');			
						var mon_det = pFloat(fila.find('.clsMDet').html());
						if (mon_det > 0 ){
						return;
						}
						
						var imp = pFloat(fila.find('.clsVal').valx());
						var mon_ret = 0;
						
						if ( total_ml >= afecto_min ) {
						mon_ret = pret * imp ;
						}
						//alert(mon_det);
						if (mon_ret > 0){
						// Si tiene detracción
						fila.find('.clsMRet').html(myRound(mon_ret));
						}			
						tot_reten = tot_reten + mon_ret;
				});
				
			}
	
	}
			
	if (cla_comp = 'FV'){
		// Retencion de Facturas
		$("#tbl_cmp_doc tbody tr").each(function(){
			var fila = $(this);
			var pag = pFloat(fila.find('.clsVal').valx());
			var imp = pFloat(fila.find('.clsImp').valx());
			//var pret = pFloat(fila.find('.clsPRet').val());			
			var vret = imp * (pret * 0.01);
			if (!fila.find('.clsPRet').is(":checked")){
			vret = 0;
			}
			if (pag <= vret && pag > 0 ){
				fila.find('.clsVal').val('');
				calcDocsComp();
			}
			fila.find('.clsMRet').html(myRound(vret));
		});
	
	}
	
	//}
}

function calcDocsComp(){
	//alert('');
	var ndoc = '';
	var tot_sum = 0;
	$("#tbl_cmp_doc tbody tr").not(".trLast").each(function(){
		var fila=$(this);
		var doc = fila.find('.clsDoc');
		//alert(doc.prop("tagName"));
		if (doc.prop("tagName")=="INPUT"){
		// Buscar Documento
			ndoc = doc.val();		
			if ($.trim(doc.val()) == "" || doc.val() == 0)
			return;
			
			if ($("#tbl_cmp_doc tbody .clsDoc[title="+ndoc+"]").length > 0 ){
			showError("El Documento "+ndoc+" ya fue ingresado previamente para este pago.");
			return;
			}
						
			doc.txtLoad();
			$.post('Procesos/Opers/OperCompens.php',
			{
			oper : 'getDoc',
			doc : doc.val(),
			tipo : GEBI('cb_comp_type').value
			}
			,function(d){
			//alert(d);
			ndoc = doc.val();
			var obj = eval("("+d+")");
			if (obj.doc == 0)
			{
			doc.val('');
			//fila.find('.clsNom').html('No existe');
			showError('Documento '+ndoc+' no existe.');
			}
			else if(obj.doc == -1){
			doc.val('');
			showError('Documento '+ndoc+' ya está compensado.');
			}
			else if(obj.doc == -2){
			doc.val('');
			showError('Documento '+ndoc+' ya fue compensado en su totalidad');
			}
			else if (obj.moneda != GEBI('cb_cmp_mon').value){
			showError('Moneda del Documento '+ndoc+', no es la misma que el Doc.Pago');
			obj.nom = ''; obj.fecha = '';obj.importe = '';obj.moneda = '';obj.vencim = '';obj.comp = '';obj.ref='';
			}
			
			else {
			
			doc.after("<span class='clsDoc' title='"+ndoc+"' style='font-weight:bold'>"+ndoc+"</span>");
			doc.remove();			
				var comp = pFloat(fila.find('.clsVal').val());
				//var imp = pFloat(fila.find('.clsImp').html());
				var pag = pFloat(fila.find('.clsComp').html());
				if (comp>pag){
					comp = pag;
				}
				else if (comp<0){
					comp = 0;
				}
				
				fila.find('.clsVal').val(myRound(comp));
				var sald = pag - comp;
				fila.find('.clsSald').html(myRound(sald));			
				
			}
			
			
			fila.find('.clsNom').html(obj.nom);
			fila.find('.clsFec').html(obj.fecha);
			fila.find('.clsImp').html(myRound(obj.importe));
			fila.find('.clsMon').html(obj.moneda);
			fila.find('.clsRef').html(obj.ref);
			fila.find('.clsVen').html(obj.vencim);
			fila.find('.clsComp').html(myRound(obj.saldo));
			doc.etxtLoad();
			
			
			});
		}
		
		else {
		// Si es SPAN
		
			var comp = pFloat(fila.find('.clsVal').val());
			//var imp = pFloat(fila.find('.clsImp').html());
			var pag = pFloat(fila.find('.clsComp').html());
			if (comp>pag){
				comp = pag;
			}
			else if (comp<0){
				comp = 0;
			}
			fila.find('.clsVal').val(myRound(comp))
			var sald = pag - comp;
			fila.find('.clsSald').html(myRound(sald));
			
		}	
		tot_sum = tot_sum + pFloat(fila.find('.clsVal').val());
		
	});
	//alert('');
	GEBI('sp_sum_pago').innerHTML = myRound(tot_sum);
	calcDocsComp_2();
}

function nuevaComp(){
loadPage('Procesos/MantCompensaciones.php');
}

function saveComp(){

	if (!$("#tbl_cmp_dat").checkInput()){
	return;
	}
	
	var suma = pFloat(GEBI('sp_sum_pago').innerHTML);
	var mont = pFloat(GEBI('t_cmp_md').value);
	
	if (suma!=mont){
	showError('La suma total en documentos no es igual al Monto de Pago');
	return;
	}
	
	var items = '';
	
	var cnt = 0;
	
	$("#tbl_cmp_doc tbody tr").not(".trLast").each(function(){
		var fila = $(this);
		var doc = fila.find('.clsDoc');
		if (doc.prop("tagName")=="SPAN"){
		var monto = pFloat(fila.find('.clsVal').val());
		var iret = (fila.find('.clsPRet').is(":checked")?1:0);
		if (monto == 0){
			fila.remove();
			return;
		}
		items = items + doc.html() + '|' + monto +  '|' + iret + '#';
		cnt = cnt + 1;
		}
		else
		{
		fila.remove();
		}
	});
	
	if (cnt == 0){
	showError('No hay documentos para compensar en la lista');
	return;
	}
		
	sendData('Procesos/Opers/OperCompens.php',
	{
	oper : 'save',
	fecha : GEBI('t_cmp_fecdoc').value,
	refer : GEBI('t_cmp_ref').value,
	emisor : GEBI('t_codemi').value,
	monto : mont,
	itf : GEBI('t_cmp_itf').value,
	via : GEBI('cb_via_pag').value,
	moneda : GEBI('cb_cmp_mon').value,
	agencia : GEBI('cb_cmp_bco').value,
	clase : GEBI('cb_comp_type').value,
	items : items
	},
	function()
	{
	});
}

function searchEmisor(){
	var clase = GEBI('cb_comp_type').value;
	if (clase == 'FC'){
		loadPopup({ url : 'Consultas/findProveedor.php', params : { return : 'showCmpProv' } });
	}
	else if(clase == 'FV'){
		loadPopup({ url : 'Consultas/findCliente.php', params : { return : 'showCmpCli' } });
	}
}

function showCmpCli(obj){
		GEBI('t_codemi').value = obj.id;
		GEBI('t_nomemi').value = obj.nom;
		GEBI('t_diremi').value = obj.dir;
}

function showCmpProv(obj){
	var clase = GEBI('cb_comp_type').value;
	 
	//if (clase  == 'FC'){
		GEBI('t_codemi').value = obj.id;
		GEBI('t_nomemi').value = obj.nom;
		GEBI('t_diremi').value = obj.dir;
	//}
	//GEBI('t_codemi').value = prv;
}

function noEditComp(){
$('#tbl_cmp_dat input,#tbl_cmp_dat select').disable();
}

function enterComp(e){
	if (e.keyCode!=13)
	return;
	
	var doc = GEBI('t_comp_ndoc').value;
	
	loadPage('Procesos/MantCompensaciones.php',
	{
		oper : 'view',
		doc : doc
	}
	);
}

function anularComp(){
	var doc = GEBI('sp_comp_nd').innerHTML;
	if (!confirm('Confirme para anular el documento '+doc))
	return;
	
	sendData('Procesos/Opers/OperCompens.php',
	{
	oper : 'anularComp',
	doc : doc
	});
}



function getCmpDocPendientes(f1,f2){
//	alert(f1);alert(f2);
	var code = GEBI('t_codemi').value;
	var moneda = GEBI('cb_cmp_mon').value;
		
	if (pInt(code)<=0){
	showError('Debe indicar el Codigo de Acreedor o Deudor');
	return;
	}
	
	if (f1 == null && f2 == null ){
	loadPopup({url : "Consultas/QueryFecs.php", params : { 'return' : 'getCmpDocPendientes', moneda : moneda }});
	return;
	}
	//alert('');
	var clase = GEBI('cb_comp_type').value;
	$('#sp_loader').show();
	$.post('Procesos/Opers/OperCompens.php',
	{ oper : 'getPend' , clase : clase , moneda : moneda, fini : f1 , ffin : f2, code : code},
	function(data){
	//alert(data);
		$('#sp_loader').hide();
		var docs = eval('(' + data + ')');
		
		$("#tbl_cmp_doc tbody tr").not(".trLast").remove();
		
		for(var x in docs){
		var obj = docs[x];
		var fila = addDocComp();
			fila.find('.clsDoc').after("<span class='clsDoc' title='"+obj.doc+"' style='font-weight:bold'>"+obj.doc+"</span>").remove();			
			fila.find('.clsNom').html(obj.nom);
			fila.find('.clsFec').html(obj.fecha);
			fila.find('.clsImp').html(myRound(obj.importe));
			fila.find('.clsMon').html(obj.moneda);
			fila.find('.clsRef').html(obj.ref);
			fila.find('.clsVen').html(obj.vencim);
			fila.find('.clsComp').html(myRound(obj.saldo));
			fila.find('.clsRD').html(myRound(obj.rd));
			fila.find('.clsIgv').html(myRound(obj.igv));
			fila.find('.clsVal').val(myRound('0'));
			fila.find('.clsPDet').html(myRound(obj.i_det));
			//fila.find('.clsPDet').html(myRound(obj.i_det));			
			//var sald = pag - comp;
			//fila.find('.clsSald').html(myRound(obj.saldo));		
		}
		calcDocsComp();
	});	
}

chgClaComp(false);
</script>
